<?php
/**
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 */

class ItemsController extends AppController
{
    # Controller Name to be used
    var $name = 'Items';

    # Models to be used
    var $uses = array(
        'Item',
        'Product'
    );

    # set the layout to use
    var $layout = 'items_layout';

    # set the name of this module
    var $moduleName = 'Items';

    # Check the authenticity of the user
    function  beforeFilter()
    {
        parent::beforeFilter($this->moduleName);
        parent::setUpGlobalConfig();
    }

    # Controller actions
    /**
     * This function displays all the users in the system
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index()
    {
        /*$products_data = $this->Product->find('all', array('condition' => array('delete' => 'n'), 'recursive' => -1));
        //debug($products_data);
        $products = array();
        foreach ($products_data as $value) {
            $name = strtoupper($value['Product']['name']);
            $products[$name] = $name;
        }*/

        $currency_opts = $this->currency_types;
        $buying_usd_rate = $this->buying_usd_rate;
        $selling_usd_rate = $this->selling_usd_rate;

        $page_title = 'Items Managements';

        $this->set(compact('page_title','currency_opts', 'products', 'buying_usd_rate', 'selling_usd_rate'));
    }

    /**
     * This function add a new record to the database
     * @name add
     * @param void
     * @return Json data
     * @access public
     */
    function add()
    {
        # Get the user session data
        $loggedUser = $this->Auth->user();
        # check whether the HTTP Request is an ajax request
        if ($this->request->is('ajax')) {
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            # retrieve the model
            $model = ucfirst($_POST['model']);
            # Check the model
            switch ($model) {
                case 'Item' :
                    $upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    $loggedUser_id = $loggedUser['id'];

                    $this->request->data['Item']['name'] = strtoupper($this->request->data['Item']['name']);

                    if ($this->request->data['Item']['currency'] == '$') {
                        $this->request->data['Item']['cedi_amount'] = doubleval($this->request->data['Item']['amount']) * doubleval($this->request->data['Item']['usd_rate']);
                    }
                    else {
                        $this->request->data['Item']['cedi_amount'] = doubleval($this->request->data['Item']['amount']);
                    }

                    if ($this->request->data['Item']['insurance_currency'] == '$') {
                        $this->request->data['Item']['insurance_cedi_amt'] = doubleval($this->request->data['Item']['insurance_amt']) * doubleval($this->request->data['Item']['usd_rate']);
                    }
                    else {
                        $this->request->data['Item']['insurance_cedi_amt'] = doubleval($this->request->data['Item']['insurance_amt']);
                    }

                    if ($upt_id) {
                        /** Edit*/
                        $this->Item->id = $upt_id;
                        $this->request->data['Item']['modified_by'] = $loggedUser_id;
                    }
                    else {
                        /** New*/
                        $this->Item->create();
                        $this->request->data['Item']['created_by'] = $loggedUser_id;
                    }

                    # save the data
                    if ($this->Item->save($this->request->data)) {
                        return json_encode(array('code' => 0, 'mesg' => __('Data Saved')));
                    }
                    else {
                        return json_encode(array('code' => 1, 'mesg' => $this->Item->invalidFields()));
                    }
                    break;
            }
        }
    }


    /**
     *
     * @param void
     * @return html
     * @access public
     */
    function load()
    {
        $this->autoRender = false;
        $this->autoLayout = false;

        /** Loading */
        $userData = $this->Item->getById($_POST['data-id']);

        if ($userData) {
            return json_encode(array('code' => 0, 'data' => $userData, 'mesg' => __('Data Found')));
        }
        else {
            return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
        }
    }


    #
    function delete_()
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            $loggedUser =  $this->Auth->user();
            $loggedUser_id = $loggedUser['id'];

            $ids = $_POST['ids'];
            $modObj = ClassRegistry::init('Item');
            $result = $modObj->updateAll(
                array('Item.deleted' => "'y'",'Item.modified_by' => $loggedUser_id),
                array('Item.id' => $ids)
            );

            if ($result) {
                echo json_encode(array('code' => 0, 'mesg' => __('Selected Item(s) have been successfully deleted')));
            }
            else {
                echo json_encode(array('code' => 1, 'mesg' => __('Selected Item(s) cannot be deleted')));
            }
        }
    }


    /**
     * @name get
     * @param void
     * @return Json Data
     */
    function get()
    {
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        /** The current page */
        $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
        /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
        /** Sort order */
        $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
        /** Search column */
        $search_query = isset($_POST['query']) ? $_POST['query'] : '';
        /** Search string */
        $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
        $limit = $rp;
        $start = ($page - 1) * $rp;

        $condition_array = array('Item.deleted' => 'n');
        if (!empty($search_query)) {
            if ($qtype == 'name') {
                $condition_array = array(
                    'Item.name LIKE' => $search_query . '%',
                    'Item.deleted' => 'n'
                );
            }
            else {
                $condition_array = array(
                    "Item.$qtype LIKE" => $search_query . '%',
                    'Item.deleted' => 'n'
                );
            }
        }


        //$fields = array('Item.id','Item.name','Item.currency','Item.amount','Item.interest','Item.comments');
        //$users = $this->Item->find('all', array('fields'=>$fields,'conditions' => $condition_array,'order' => "Item.$sortname $sortorder",'limit' => $start.','.$limit,'recursive' => -1));
        $users = $this->Item->find('all', array('conditions' => $condition_array, 'order' => "Item.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
        $usersCount = $this->Item->find('count', array('conditions' => $condition_array, 'recursive' => -1));

        $total_records = $usersCount;

        if ($users) {
            $return_arr = array();
            foreach ($users as $obj) {
                $return_arr[] = array(
                    'id' => $obj['Item']['id'],
                    'cell' => array(
                        $obj['Item']['id'],
                        strtoupper($obj['Item']['name']),
                        strip_tags($obj['Item']['specs']),
                        $obj['Item']['currency'],
                        $this->formatNumber($obj['Item']['amount'], 'money'),
                        $this->formatNumber($obj['Item']['usd_rate'], 'money'),
                        $this->formatNumber($obj['Item']['cedi_amount'], 'money'),
                        $obj['Item']['comments']
                    )
                );
            }
            return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
        }
        else {
            return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
        }

    }

}

?>
